package com.wushijia.java8.time;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Duration;
import org.joda.time.Interval;
import org.joda.time.LocalDate;
import org.joda.time.Period;
import org.joda.time.PeriodType;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class JodaDemo {

  public static void main(String[] args) {
    Calendar calendar = Calendar.getInstance();
    //2000年1月1日0时0分0秒
    calendar.set(2000, Calendar.JANUARY, 1, 0, 0, 0);
    //使用joda-time，始终与时区相关，不指定它的话，它将默认设置我为运行代码机器所在的时区
    DateTime dateTime = new DateTime(2000, 1, 1, 0, 0, 0);

    //datetime可接受多种类型参数构造函数,并且可以互相转换
    Date date = new Date();
    DateTime dateTime1 = new DateTime(date.getTime());
    DateTime dateTime2 = new DateTime(calendar);
    Date date1 = dateTime1.toDate();
    Calendar calendar1 = dateTime2.toCalendar(Locale.CHINA);
    DateTime dateTime3 = new DateTime("2017-12-12");
    System.out.println(dateTime1.toString("E MM/dd/yyyy HH:mm:ss.SSS"));

    //在此日期基础上加上90天
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("E MM/dd/yyyy HH:mm:ss.SSS");
    calendar.add(Calendar.DAY_OF_MONTH, 90);
    System.out.println(simpleDateFormat.format(calendar.getTime()));

    //使用joda-time
    System.out.println(dateTime.plusDays(90).toString("E MM/dd/yyyy HH:mm:ss.SSS"));

    //在此时间之后45天的某天的下个月的当前周的最后一天的日期
    dateTime = dateTime.plusDays(45).plusMonths(1).dayOfWeek().withMaximumValue();
    System.out.println(dateTime.toString("E MM/dd/yyyy HH:mm:ss.SSSa ZZZZ"));

    //并且兼容Calendar
    calendar.setTime(dateTime.toDate());
    System.out.println(simpleDateFormat.format(calendar.getTime()));

    //格式化输出
    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    DateTime dateTime4 = DateTime.parse("2017-12-12 21:23:22", formatter);
    String dateTime4_str = dateTime4.toString("E yyyy/MM/dd HH:mm:ss", Locale.CHINA);
    System.out.println(dateTime4_str);

    //计算两个日期之间的相差
    LocalDate localDate1 = new LocalDate(2017, 12, 11);
    LocalDate localDate2 = new LocalDate(2017, 12, 15);
    System.out.println(Days.daysBetween(localDate1, localDate2).getDays());

    //计算区间毫秒数
    Duration duration = new Duration(dateTime1, dateTime2);
    long millis = duration.getMillis();
    System.out.println(millis);
    //计算区间天数
    Period period = new Period(dateTime1, dateTime2, PeriodType.days());
    int days = period.getDays();
    System.out.println(days);
    //计算特定日期是否在该区间内
    Interval interval = new Interval(dateTime2, dateTime1);
    boolean contained = interval.contains(new DateTime("2017-10-12"));
    System.out.println(contained);

    //日期比较，和系统比较
    System.out.println(dateTime1.isAfterNow());
    dateTime1.isBeforeNow();
    dateTime1.isEqualNow();
    System.out.println(dateTime1.isBefore(dateTime2));


  }
}
